"""
File Name: Pycharm
Description:   twitter_server
Author: Panwj
Date: 2025/9/6 6:59
"""
import time
from urllib.parse import urlsplit

import jmespath

from src.action.base_bot import BaseBot


class TwitterServer(BaseBot):
    name = "tw"

    def __init__(self):
        super().__init__()
        self.home_url = 'https://x.com'

    def check_post_comment(self, context):
        res = self.page.listen.wait(timeout=6, raise_err=False)
        if res:
            data_json = res.response.body
            comment_id = jmespath.search('data.create_tweet.tweet_results.result.rest_id', data_json)
            return comment_id
        else:
            self.page.listen.start('/TweetDetail')
            self.page.refresh()
            res = self.page.listen.wait(timeout=6, raise_err=False)
            if res:
                # todo 校验，评论是否成功, 或者通过评价接口校验
                data_json = res.response.body
        return None

    def get_post_like_count(self, post_url):
        # 可使用twitter api 直接获取
        post_id = post_url[post_url.rfind('/') + 1:]
        res = self.page.listen.wait(timeout=20, raise_err=False)
        if res:
            data_json = res.response.body
            instructions = jmespath.search('data.threaded_conversation_with_injections_v2.instructions', data_json)
            for each_instruction in instructions:
                if each_instruction.get('type', '') == 'TimelineAddEntries':
                    entries = each_instruction.get('entries', [])
                    for each_entry in entries:
                        if post_id in each_entry['entryId']:
                            return jmespath.search('content.itemContent.tweet_results.result.legacy.favorite_count',
                                                   each_entry)
            return None

    def comment_comment(self, url, content):
        return self.comment_post(url, content)

    def like_comment(self, url):
        self.page.listen.start('/TweetDetail')
        self.page.get(url)
        before_like_count = self.get_post_like_count(url)
        # 找到评论位置
        article_elements = self.page.wait.ele_displayed('xpath://div[@aria-label="Timeline: Conversation"]/div')
        url_path = urlsplit(url).path
        for each_article in article_elements.children():
            a_tags = each_article.eles('tag:a')
            for a_tag in a_tags:
                href = a_tag.attr('href')
                if url_path in href:
                    like_button = each_article.ele('xpath://button[@data-testid="like"]', timeout=20)
                    like_button.click()
                    self.page.refresh()
                    after_like_count = self.get_post_like_count(url)
                    return {'code': 200, "msg": f"{url} 点赞成功",
                            'data': {"like_count_before": before_like_count, 'after_like_count': after_like_count}}
        return {'code': 500, "msg": f"{url} 点赞失败",
                'data': {"like_count_before": before_like_count, 'after_like_count': None}}

    def like_post(self, post_url):
        """
        点赞帖子
        :return:
        """
        self.page.listen.start('/TweetDetail')
        self.page.get(post_url)
        before_like_count = self.get_post_like_count(post_url)
        like_button = self.page.wait.ele_displayed('xpath://button[@data-testid="like"]', timeout=20)
        if like_button:
            like_button.click()
            # 校验点赞是否成功
            self.page.refresh()
            after_like_count = self.get_post_like_count(post_url)
            return {'code': 200, "msg": f"{post_url} 点赞成功",
                    'data': {"like_count_before": before_like_count, 'after_like_count': after_like_count}}
        return {'code': 500, "msg": f"{post_url} 点赞失败",
                'data': {"like_count_before": before_like_count, 'after_like_count': None}}

    def comment_post(self, post_url, comment_conet):
        try:
            self.page.get(post_url)
            # 等待评论框加载
            reply_button = self.page.wait.ele_displayed('xpath://span[text()="Reply"]', timeout=20)

            if reply_button:
                editor = self.page.ele('xpath://div[@class="public-DraftEditorPlaceholder-inner"]')

                editor.click()

                editor.input(comment_conet)
                time.sleep(2)
                submit_button = self.page.wait.ele_displayed(
                    'xpath://span[text()="Reply"]/ancestor::button[@data-testid="tweetButtonInline"]', timeout=10)
                if submit_button:
                    self.page.listen.start('/CreateTweet')
                    submit_button.click()
                    comment_id = self.check_post_comment(comment_conet)
                    return {'code': 200, "msg": f"{post_url} 帖子成功", 'data': {"comment_id": comment_id}}
                else:
                    return {'code': 500, "msg": f"{post_url} 帖子评论异常， 异常原因：未正常提交评论"}

            else:
                return {'code': 500, "msg": f"{post_url} 帖子不存在或者页面加载不成"}
        except Exception as e:
            return {'code': 500, "msg": f"{post_url} 帖子评论异常， 异常原因：{str(e)}"}


if __name__ == "__main__":
    TwitterServer().start_action()
